package owg.util.awt;

import java.io.File;
import java.io.Serializable;

import javax.swing.filechooser.FileFilter;

public class ExtensionFilter extends FileFilter implements Serializable
	{
	private static final long serialVersionUID = -3616345155445669120L;
	public final String[] extension;
	public final String name;
	/**
	 * @param name The name of the file type
	 * @param extension The file extension for the file type. For optimal results, this should include the dot.
	 */
	public ExtensionFilter(String name,String extension)
		{
		this(name, new String[]{extension});
		}
	/**
	 * @param extension The file extension for the file type. For optimal results, this should include the dot.
	 */
	public ExtensionFilter(String extension)
		{
		this(extension, new String[]{extension});
		}
	/**
	 * @param name The name of the file type
	 * @param extension The possible file extensions for the file type. For optimal results, these should include the dot.
	 */
	public ExtensionFilter(String name,String[] extension)
		{
		this.name = name;
		this.extension = extension;
		}

	/**
	 * @param extension The possible file extensions for the file type. For optimal results, these should include the dot.
	 */
	public ExtensionFilter(String[] extension)
		{
		this(toString(extension), extension);
		}
	@Override
	public boolean accept(File f)
		{
    	if(f == null)
    		return true;
		if (f.isDirectory())
            return true;
		boolean result = false;
		for(int i=0; i<extension.length; i++)
			{
			if(f.getName().endsWith(extension[i]))
				result = true;
			}
		return result;
		}
	    //The description of this filter
    public String getDescription() 
    	{
        return name;
		}
    private static String toString(String[] extensions)
    	{
    	StringBuilder sb = new StringBuilder();
    	sb.append(extensions[0]);
    	for(int i = 1; i<extensions.length; i++)
    		{
    		sb.append("|");
    		sb.append(extensions[i]);
    		}
    	return sb.toString();
    	}
    @Override
    public String toString()
    	{
    	return name;
    	}
	}
    